<?php
use Michelf\Markdown;
use Phalcon\Mvc\View;

class IndexController extends ControllerBase
{

    public function indexAction()
    {
        $this->tag->prependTitle("工作台 - ");
        $loginHistory = [];
        $rows         = MsLog::find(
            [
                "uid = '" . $this->auth['id'] . "'",
                "order" => "id DESC",
                "limit" => 10,
            ]
        );
        $action = ['login' => '登录'];
        if ($rows) {
            $rows = $rows->toArray();
            foreach ($rows as $key => &$value) {
                $value['action']       = $action[$value['action']];
                $value['created_time'] = Common::contextualTime($value['created_time']);
                $loginHistory[]        = $value;
            }
        }
        $this->view->loginHistory = $loginHistory;

        $this->view->dir = Common::endecrypt('_post/');
    }

    public function editorbakAction()
    {
        $filename = $this->request->getQuery('f');
        $file     = file_get_contents(BASE_PATH . '/_post/' . $filename);
        $arr      = explode('-------------------------------------', $file);
        $first    = explode(PHP_EOL, $arr[0]);
        //title
        $title                 = explode(':', $first[0]);
        $this->view->$title[0] = $title[1];
        //intro
        $intro                 = explode(':', $first[1]);
        $this->view->$intro[0] = $intro[1];
        $this->view->content   = $arr[1];
        $this->view->filename  = $filename;
        $this->tag->setTitle($filename . ' - 编辑文章');
        $this->view->dir = Common::endecrypt('_post/');
    }

    public function fileSaveAction()
    {
        header("Content-type:application/json;charset=utf-8");
        $file    = $this->request->getPost('file');
        $title   = $this->request->getPost('title');
        $intro   = $this->request->getPost('intro');
        $content = $this->request->getPost('content');
        $md      = "title:" . $title . PHP_EOL;
        $md .= "intro:" . $intro . PHP_EOL;
        $md .= PHP_EOL;
        $md .= "-------------------------------------";
        $md .= PHP_EOL;
        $md .= $content;
        file_put_contents(BASE_PATH . '/_post/' . $file, $md);
        echo json_encode(['resultCode' => 200, 'message' => 'OK']);
        die;
    }

    /**
     * 读取目录接口
     *
     * @author liqiming
     * @date   2018-12-26
     * @return [type]     [description]
     */
    public function getdirAction($path)
    {
        $path = Common::endecrypt($path, 'decrypt');
        $file = Common::getDirContent(BASE_PATH . '/' . $path);
        $json = ['path' => rtrim($path, '/'), 'data' => $file];
        $this->response->setJsonContent($json);
        return $this->response;
    }

    /**
     * 登录&注册面板
     *
     * @return mixed
     */
    public function authAction()
    {
        $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
    }

    public function signinAction()
    {
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
        $username = $this->request->getPost('username', ['trim', 'string']);
        $password = $this->request->getPost('password', ['trim', 'alphanum']);
        $row      = MsMember::findFirst(
            [
                "conditions" => "username = ?1",
                "bind"       => [
                    1 => $username,
                ],
            ]
        );
        $json = ['code' => 1, 'msg' => '帐号不存在'];
        if ($row) {
            $json = ['code' => 2, 'msg' => '密码不正确'];
            if ($this->security->checkHash($password, $row->password)) {
                $json = ['code' => 0, 'msg' => null, 'url' => '/index/index'];
                //验证成功后，写入Cookies用于权限验证
                $auth = [
                    'id'           => $row->id,
                    'account'      => $row->email,
                    'username'     => $row->username,
                    'group'        => $row->group,
                    'created_time' => $row->created_time,
                ];
                $auth = serialize($auth);
                $this->cookies->set('auth', $auth, time() + 15 * 86400);
                //写入操作日志
                $msLog               = new MsLog();
                $msLog->action       = 'login';
                $msLog->username     = $row->username;
                $msLog->uid          = $row->id;
                $msLog->created_time = time();
                if ($msLog->save() === false) {
                    $this->logger->error('写入日志失败 ' . __LINE__); //将错误记录日志，便于今后分析。
                }
            }
        }
        $this->response->setJsonContent($json);
        return $this->response;
    }

    public function logoutAction()
    {
        $this->cookies->get('auth')->delete();
        $this->response->redirect('/index/auth', true);
    }

    public function error404Action()
    {
        $this->response->setStatusCode(404, 'Not Found');
        $this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);
    }

    public function applistAction()
    {
        $this->tag->prependTitle("插件列表 - ");
        $this->assets->addJs("/common/js/common.js");

        $file = file_get_contents(BASE_PATH . '/_app/config.json');
        $file = json_decode($file, true);
        foreach ($file as $key => &$value) {
            $tmp = [];
            foreach ($value['group'] as $v) {
                $tmp[] = $this->group[$v];
            }
            if (in_array($key, $this->userapp)) {
                $value['use'] = 1;
            } else {
                $value['use'] = 0;
            }
            $value['group'] = $tmp;
            unset($value);
        }
        $this->view->app = $file;
    }

    public function designerAction()
    {
        echo 'designer';
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
    }
    public function bossAction()
    {
        echo 'boss';
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
    }
    public function editorAction()
    {
        echo 'editor';
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
    }
    public function sellerAction()
    {
        echo 'seller';
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
    }
    public function responderAction()
    {
        echo 'responder';
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
    }
    public function guestAction()
    {
        echo 'guest';
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
    }

    public function errorAction()
    {
        $this->response->setStatusCode(503, 'Service Unavailable');
        $this->view->message = $this->dispatcher->getParam('message');
        $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
    }

    /**
     * 安装应用，根据应用使用的角色，不适用的角色没有办法安装应用。
     * 安装俺完成后，需要刷新一下acl，不然会提示无权限访问。
     *
     * @author liqiming
     * @date   2018-12-29
     * @param  [type]     $identifier [description]
     * @return [type]                 [description]
     */
    public function installappAction($identifier)
    {
        /**
         * 验证用户所在的用户组是否可以安装此应用
         */
        $appConfig = file_get_contents(BASE_PATH . '/_app/config.json');
        if (!$appConfig) {
            throw new Exception("读取应用列表异常", 1);
        }
        $appConfig = json_decode($appConfig, true);
        if (!$appConfig) {
            throw new Exception("解析应用列表异常", 1);
        }
        if (!in_array($this->auth['group'], $appConfig[$identifier]['group'])) {
            $json = ['code' => 1, 'msg' => '该用户组无法安装此应用'];
        } else {
            /**
             * 验证用户是否安装了此应用，如果没有安装则可以安装，安装了则不再安装
             */
            $member = MsMember::findFirst($this->auth['id']);
            $app    = [];
            if ($member->app) {
                $app = unserialize($member->app);
                foreach ($app as $key => $value) {
                    $tmp[] = $value['identifier'];
                }
            }
            if (in_array($identifier, $tmp)) {
                $json = ['code' => 2, 'msg' => '已经安装过了'];
            } else {
                $app[]       = ['identifier' => $identifier, 'time' => time()];
                $member->app = serialize($app);
                $member->save();
                $json = ['code' => 0, 'msg' => null];

                //更新权限
                $acl = $this->redis->get('uid:' . $this->auth['id'] . ':acl');
                if ($acl) {
                    $acl = unserialize($acl);
                } else {
                    $acl = unserialize($this->redis->get('base:acl'));
                }
                $acl->addResource(new Phalcon\Acl\Resource($identifier), $appConfig[$identifier]['resource']);
                foreach ($appConfig[$identifier]['resource'] as $k => $val) {
                    $acl->allow($this->auth['group'], $identifier, $val);
                }
                $this->redis->set('uid:' . $this->auth['id'] . ':acl', serialize($acl));
                //安装的应用写入缓存
                $this->redis->set('uid:' . $this->auth['id'] . ':app', serialize($app));
            }
        }

        $this->response->setJsonContent($json);
        return $this->response;
    }

    public function readmeAction()
    {
        $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
        $markdownFile = BASE_PATH . '/README.md';
        if (!file_exists($markdownFile)) {
            return $this->response->setStatusCode(404, "Not Found");
        }
        $markdown = file_get_contents($markdownFile);
        $content  = Markdown::defaultTransform($markdown);
        $content .= "<hr /><p class=\"text-center text-muted\">此文档基于README.md生成，最后编辑时间：" . date('Y-m-d H:i:s', filemtime($markdownFile)) . " <a href=\"/\">返回首页</a></p>";

        $this->view->content = $content;
    }

    public function editoruploadAction()
    {
        $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
        header("Content-Type:application/json; charset=utf-8");
        $siteid   = $this->request->getQuery('siteid');
        $savePath = BASE_PATH . '/_site/' . $siteid . '/asset/';
        $saveURL  = '/_site/' . $siteid . '/asset/';
        $formats  = array('gif', 'jpg', 'jpeg', 'png', 'bmp');

        $name = 'editormd-image-file';

        if (isset($_FILES[$name])) {
            $imageUploader = new EditorMdUploader($savePath, $saveURL, $formats, 1, 'Ymdhis');

            $imageUploader->config(array(
                'maxSize' => 1024, // 允许上传的最大文件大小，以KB为单位，默认值为1024
                'cover'   => true, // 是否覆盖同名文件，默认为true
            ));

            if ($imageUploader->upload($name)) {
                $imageUploader->message('上传成功！', 1);
            } else {
                $imageUploader->message('上传失败！', 0);
            }
        }
    }
}
